package com.example.question.list.list1;

import java.io.UnsupportedEncodingException;

/**
 * @Date 2023-07-05
 * @Author Jonathan
 * @link {<a href="https://leetcode.cn/problems/rotate-list/">...</a>}
 */
public class Code12_61 {
    Integer index = 0;

    public static void main(String[] args) throws UnsupportedEncodingException {
        Code12_61 code = new Code12_61();
        ListNode listNode = List.createList(new int[]{1, 2, 3, 4, 5});
        ListNode node = code.rotateRight(listNode, 13);
        List.printLink(node);
    }

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) {
            return head;
        }
        // 计算这个链表长度
        int length = 0;
        ListNode cur = head;
        ListNode last = null;
        do {
            if (cur.next == null) {
                last = cur;
            }
            cur = cur.next;
            length++;
        } while (cur != null);
        k = k % length;
        cur = head;
        for (int i = 1; i < (length - k); i++) {
            cur = cur.next;
        }
        last.next = head;
        ListNode newHead = cur.next;
        cur.next = null;
        return newHead;
    }
}
